package activity.addCamera;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.hichip.campro.R;
import java.util.ArrayList;
import java.util.List;
import activity.addCamera.adapter.WiFiListAdapter;
import base.HiActivity;
import butterknife.BindView;
import common.TitleView;
/**
 * 选择设备热点(AP)Activity
 * Created by lt on 2017\12\20 0020.
 */
public class SeleDevHotSpotActivity extends HiActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
    @BindView(R.id.titleview) TitleView titleview;
    @BindView(R.id.progressbar) ProgressBar progressbar;
    @BindView(R.id.tv_not_search_device) TextView tv_not_search_device;
    @BindView(R.id.lv_wifi_list) ListView lv_wifi_list;

    private WiFiListAdapter mAdapter;
    private List<ScanResult> myScanResult = new ArrayList<ScanResult>();
    private String mCurrentPhoneWiFi;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_ap_mode_add_camera;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getIntentData();
        intiView();
        setAdapter();
        inintData();
        setListeners();
    }

    private void getIntentData() {
        mCurrentPhoneWiFi=getIntent().getStringExtra("mCurrentPhoneWiFi");
    }


    private void setListeners() {
        lv_wifi_list.setOnItemClickListener(this);
        tv_not_search_device.setOnClickListener(this);
    }

    private void setAdapter() {
        mAdapter = new WiFiListAdapter(this, myScanResult);
        lv_wifi_list.setAdapter(mAdapter);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 110:
                if (grantResults.length>0&&grantResults[0] == PackageManager.PERMISSION_GRANTED){// 允许
                    handScan();
                }else{// 不允许
                    Toast.makeText(this,getString(R.string.no_permission),Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void handScan() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        wifiManager.startScan();
        WifiInfo info=wifiManager.getConnectionInfo();
        List<ScanResult> scanResults = wifiManager.getScanResults();
        for (ScanResult scanResult : scanResults) {
            String ssid = scanResult.SSID;
            if (!TextUtils.isEmpty(ssid) && ssid.length() > 5) {
                String subSSid = ssid.substring(0, 5);
                if (subSSid.equalsIgnoreCase("IPCAM")) {
                    boolean isHave=false;
                    for(ScanResult sr:myScanResult){
                        if(sr.SSID.equals(scanResult.SSID)){
                            isHave=true;
                            break;
                        }
                    }
                    if(!isHave){
                        myScanResult.add(scanResult);
                    }
                }
            }
        }
        progressbar.setVisibility(View.GONE);
        if (myScanResult.size() < 1) {
            lv_wifi_list.setVisibility(View.GONE);
            tv_not_search_device.setVisibility(View.VISIBLE);
        }else {
            lv_wifi_list.setVisibility(View.VISIBLE);
            mAdapter.notifyDataSetChanged();
        }
        titleview.setRightTxt(getString(R.string.refresh));
    }

    private void inintData() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission_group.LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // 获取wifi连接需要定位权限,没有获取权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE,}, 110);
            return;
        }else {
            handScan();
        }
    }

    private void intiView() {
        titleview.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        titleview.setTitle(getString(R.string.title_find_device_spot));
        titleview.setButton(TitleView.NAVIGATION_BUTTON_RIGHT);
        titleview.setRightTxt(getString(R.string.refresh));
        titleview.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {
            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        SeleDevHotSpotActivity.this.finish();
                        break;
                    case TitleView.NAVIGATION_BUTTON_RIGHT:
                        tv_not_search_device.setVisibility(View.GONE);
                        titleview.setRightTxt(getString(R.string.searching));
                        if (mAdapter != null) {
                            myScanResult.clear();
                            lv_wifi_list.setVisibility(View.GONE);
                            progressbar.setVisibility(View.VISIBLE);
                        }
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                inintData();
                            }
                        }, 1000);
                        break;
                }
            }
        });

        tv_not_search_device.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tv_not_search_device.getPaint().setAntiAlias(true);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    // listView 列表点击事件
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String SSID=myScanResult.get(position).SSID;
        Intent intent = new Intent(SeleDevHotSpotActivity.this, APConnectActivity.class);
        intent.putExtra("ssid", SSID);
        intent.putExtra("mCurrentPhoneWiFi",mCurrentPhoneWiFi);
        startActivity(intent);
        this.finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_not_search_device://未找到设备热点?
                View customView = View.inflate(SeleDevHotSpotActivity.this, R.layout.pup_not_search_dev_hot, null);
                PopupWindow popupWindow = new PopupWindow(customView);
                ColorDrawable cd = new ColorDrawable(-0000);
                popupWindow.setBackgroundDrawable(cd);
                popupWindow.setOutsideTouchable(false);
                popupWindow.setFocusable(true);
                popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
                popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
                popupWindow.showAtLocation(tv_not_search_device, Gravity.CENTER, 0, 0);
                TextView tv_know=customView.findViewById(R.id.tv_know);
                tv_know.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });
                break;
        }

    }
}
